﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace EEDS.Core
{
    public abstract class RelationshipPaletteConverter : PaletteConverter
    {
        public override Color ClosestColour(Bitmap emblem, Point pixel, Palette palette)
        {
            Color colour = emblem.GetPixel(pixel.X, pixel.Y);

            int relationshipOld;
            int relationshipNew = int.MaxValue;
            Color soFar = Color.Empty;

            if (colour.A == 0)
                return palette.BackColour;

            foreach (Color clr in palette.Colours)
            {
                relationshipOld = relationshipNew;

                relationshipNew = ColourRelationship(clr, colour);

                if (relationshipNew < relationshipOld)
                    soFar = clr;
                else
                    relationshipNew = relationshipOld;
            }

            return soFar;
        }

        public override Palette[] ClosestPalettes(Bitmap emblem, Palette[] palettes)
        {
            long relationshipOld = 0;
            long relationshipNew = long.MaxValue;
            List<Palette> soFar = new List<Palette>();

            foreach (Palette palette in palettes)
            {
                relationshipOld = relationshipNew;
                relationshipNew = 0;

                for (int x = 0; x < emblem.Width; x++)
                {
                    for (int y = 0; y < emblem.Height; y++)
                    {
                        relationshipNew += ColourRelationship(ClosestColour(emblem, new Point(x, y), palette), emblem.GetPixel(x, y));
                    }
                }

                if (relationshipNew < relationshipOld)
                {
                    soFar.Clear();
                    soFar.Add(palette);
                }
                else if (relationshipNew == relationshipOld)
                    soFar.Add(palette);
            }

            return soFar.ToArray();
        }

        public abstract int ColourRelationship(Color colourA, Color colourB);
    }
}
